package top.chenziji.Util;

import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.file.*;
import java.util.*;

public class FileUitl {

    // 定义视频文件的后缀名列表
    private static final List<String> VIDEO_EXTENSIONS = Arrays.asList(
            "mp4", "avi", "mov", "wmv", "flv", "mkv", "mpg", "mpeg"
    );

    /***
     * 扫描指定目录下的文件
     */
    public static List<Map> searcDirAllFile(String path){
        List<Map> allData = new ArrayList<>();
        // 获取当前目录
        File currentDir = new File(path);

        // 获取当前目录下的所有文件
        File[] files = currentDir.listFiles();

        if (files != null) {
            for (File file : files) {
                // 判断是否为文件且是否为视频文件
                if (file.isFile() && isVideoFile(file)) {
                    // 获取文件名和后缀名
                    String fileName = file.getName();
                    int dotIndex = fileName.lastIndexOf('.');
                    String nameWithoutExtension = fileName.substring(0, dotIndex);
                    String extension = fileName.substring(dotIndex + 1);

                    // 获取所在文件夹的绝对路径名
                    String folderPath = file.getParentFile().getAbsolutePath();

                    // 打印信息
                    System.out.println("文件名: " + nameWithoutExtension);
                    System.out.println("后缀名: " + extension);
                    System.out.println("所在文件夹绝对路径: " + folderPath);
                    System.out.println("----------");
                    Map map = new HashMap();
                    map.put("filePath",file.getAbsolutePath());
                    map.put("fileName",file.getName());
                    map.put("nameWithoutExtension",nameWithoutExtension);
                    map.put("extension",extension);
                    map.put("folderPath",folderPath);
                    allData.add(map);
                }
            }
        } else {
            System.out.println("当前目录为空或无法读取目录内容。");
        }
        return allData;
    }

    // 判断文件是否为视频文件
    private static boolean isVideoFile(File file) {
        String fileName = file.getName().toLowerCase();
        for (String ext : VIDEO_EXTENSIONS) {
            if (fileName.endsWith(ext)) {
                return true;
            }
        }
        return false;
    }

    //检查配置文件是否存在
    public static boolean InspectConfigFileCreate() throws IOException {
        // 获取用户主目录的路径
        String userHome = System.getProperty("user.home");

        File file2 =new File(userHome + "/video_pro");
        if (!file2.exists()) {
           file2.mkdirs();
        }

        File file = new File(userHome + "/video_pro/config.txt");
        if (file.exists()) {
            return true;
        }

        file.createNewFile();
        return false;
    }

    //读取配置文件内容
    public static Map ReadConfigFileCreate() throws IOException {
        Map config = new HashMap();
        // 获取用户主目录的路径
        String configPath = System.getProperty("user.home")+"/video_pro/config.txt";
        try (BufferedReader reader = new BufferedReader(new FileReader(configPath));) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] split = line.split("=");
                if(split.length>1){
                    config.put(split[0],split[1]);
                }

            }
            return config;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    // 追加数据到文件的下一行
    private static void appendToFile(String data,String FILE_PATH) {
        try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(FILE_PATH), StandardOpenOption.CREATE)) {
            writer.write(data);
            writer.newLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //读取配置文件内容
    public static boolean writeConfigFileCreate(String data) throws IOException {
        String configPath = System.getProperty("user.home")+"/video_pro/config.txt";
        appendToFile(data,configPath);
        return true;
    }

    public static boolean fileIsLock(String filePath3) {

        try {
            Path filePath = Paths.get(filePath3);
            // 尝试以写模式打开文件
            FileChannel fileChannel = FileChannel.open(filePath, StandardOpenOption.WRITE);

            // 尝试获取独占锁，如果文件已被其他进程占用，将抛出异常
            try {
                fileChannel.lock(); // 如果文件被占用，lock() 方法会阻塞或抛出异常
                System.out.println("File is not locked, it is available.");
                return false;
            } catch (IOException e) {
                System.out.println("File is currently in use or locked by another process.");
                return true;
            } finally {
                // 确保在操作完成后释放锁
                fileChannel.close();
            }

        } catch (IOException e) {
            e.printStackTrace();
            return true;
        }
    }

    public static void moveFile(String sourcePath2, String targetDir2){
        // 定义源文件和目标目录的路径
        Path sourcePath = Paths.get(sourcePath2);
        Path targetDir = Paths.get(targetDir2);

        // 解决目标文件的完整路径
        Path targetPath = targetDir.resolve(sourcePath.getFileName());

        try {
            // 移动文件到目标目录
            Files.move(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
            System.out.println("文件已成功移动到: " + targetPath);
        } catch (Exception e) {
            // 捕获并处理可能出现的异常
            System.err.println("移动文件时出错: " + e.getMessage());
        }
    }
}
